<?php

namespace app\models;

use Yii;
use yii\web\IdentityInterface;
use yii\base\NotSupportedException;

/**
 * This is the model class for table "admin".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $group_id
 */
class Admin extends \yii\db\ActiveRecord implements IdentityInterface
{
    public $password;
    public $password2;

    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'group_id'], 'integer'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'string', 'min' => 4, 'max' => 20],
            [['username'], 'unique', 'message' => '该用户名已被使用'],
            ['username', 'match', 'pattern' => '/^[A-Za-z_-][A-Za-z0-9_-]+$/'],
            ['email', 'filter', 'filter' => 'trim'],
            [['email'], 'email'],
            [['password_reset_token'], 'unique'],
            [['password', 'password2'], 'required', 'on' => 'create'],
            [['password'], 'string', 'min' => 6, 'max' => 24],
            [['password'], 'match', 'pattern' => '/^\S+$/'],
            ['password2', 'compare', 'compareAttribute' => 'password', 'on' => ['create', 'update'], 'message' => '两次密码不一样'],
            ['password2', 'confirmPwd', 'on' => 'update', 'skipOnEmpty' => false],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => '电子邮箱',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'group_id' => '用户权限组',
            'password' => '密码',
            'password2' => '确认密码',
        ];
    }

    public function getGroup()
    {
        return $this->hasOne(AdminGroup::className(), ['id' => 'group_id']);
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->setPassword($this->password);
            $this->generateAuthKey();
            $this->created_at = $this->updated_at = time();
        } else {
            if (!empty($this->password)) {
                $this->setPassword($this->password);
                $this->generateAuthKey();
            }
            $this->updated_at = time();
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            AdminLog::log("新添用户：" . $this->username, "create");
        } else {
            AdminLog::log("更新用户：旧：" . $changedAttributes['username'] . "；新：" . $this->username);
        }
    }

    public function afterDelete()
    {
        parent::afterDelete();
        AdminLog::log("删除用户：" . $this->username, "delete");
    }

    public function confirmPwd($attribute)
    {
        if ($this->password) {
            if (!$this->password2) {
                $this->addError($attribute, '请输入确认密码');
            }
        }
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }
}
